package cn.com.dashihui.web.controller;
import java.sql.SQLException;
import java.util.List;

import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.ValidateKit;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.dao.AdminSeller;
import cn.com.dashihui.web.dao.SysConfig;
import cn.com.dashihui.web.dao.User;
import cn.com.dashihui.web.service.AdminService;
import cn.com.dashihui.web.service.GoodsBaseService;
import cn.com.dashihui.web.service.RoleService;
import cn.com.dashihui.web.service.StoreService;
@RequiresAuthentication
public class AdminController extends BaseController {
	private AdminService adminService = new AdminService();
	private RoleService roleService = new RoleService();
	private GoodsBaseService service = Duang.duang(GoodsBaseService.class);
	private StoreService storeService=Duang.duang(StoreService.class);
	public void index() {
		int userid = getCurrentUser().getInt("id");
		setAttr("currUser", getCurrentUser());
		setAttr("userid", getCurrentUser().getInt("id"));
		int RoleId = adminService.findByRoleId(userid);
		setAttr("RoleId", RoleId);
		int power = 1;
		int state = 0;
		int qstate = 1;
		Record st = service.findState(userid, RoleId);
		if (st != null) {
			if (RoleId == 1) {
			} else  if (RoleId == 2){
				state = service.findState(userid, RoleId).get("state");
				power = service.findState(userid, RoleId).get("power");
			}else{
				state = service.findState(userid, RoleId).get("state");
				qstate = service.findQstate(userid).get("qstate");
			}
		}
		List<Record> jobList=roleService.findAllRoles();//职位
		List<Record> busList=storeService.findAllBus();
		List<Record> storeList=storeService.findAllStoreid(userid);//分公司
		setAttr("busList", busList);//公司
		setAttr("StoreList", storeList);
		setAttr("jobList", jobList);
		setAttr("state", state);
		setAttr("power", power);
		setAttr("qstate", qstate);
		render("index.jsp");
	}

	public void page() {
		int userid = getCurrentUser().getInt("id");
		int RoleId = adminService.findByRoleId(userid);
		String storeid = adminService.findByStoreid(userid);
		String sellerId = adminService.findBysellerId(userid);
		String tel=getPara("tel");
		String name=getPara("name");
		String sellers=getPara("sellers");
		String stores=getPara("stores");
		String jobs=getPara("jobs");
		int pageNum = getParaToInt(0, 1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		renderResult(0, adminService.findByPage(pageNum, pageSize, RoleId, storeid, sellerId,tel,name,sellers,stores,jobs));
	}

	public void toAdd() {
		int userid = getCurrentUser().getInt("id");
		int roid = adminService.getRoles(userid);
		setAttr("roid", roid);
		if (roid == 1) {
			render("ad.jsp");
		} else if (adminService.findSelleridByUserId(userid) != null && roid == 2) {
			String sellerId = adminService.findSelleridByUserId(userid).get("sellerId");
			int VipPower= adminService.findSelleridByUserId(userid).getInt("VipPower");
			setAttr("VipPower", VipPower);
			setAttr("sellerId", sellerId);
			render("add.jsp");
		} else if (roid == 3) {
			String title = adminService.findstoreidByUserId(userid).get("title");
			String storeid = adminService.findstoreidByUserId(userid).get("storeid");
			int VipPower= adminService.findstoreidByUserId(userid).getInt("VipPower");
			setAttr("VipPower", VipPower);
			setAttr("title", title);
			setAttr("storeid", storeid);
			render("add.jsp");
		} 

	}

	/**
	 * 添加
	 * 
	 * @return -1：异常，0：成功，1：用户名为空，2：用户名过长，3：用户已经存在，4：密码为空，5：密码过长，6：姓名为空，7：姓名过长，8
	 *         ：手机号码为空，9：手机号码不正确，10：备注过长
	 */
	// @RequiresPermissions("auth:admin:add")
	public void doAdd() {
		// 当前登录用户的Id
		int userid = getCurrentUser().getInt("id");
		int roidd = getParaToInt("Roid");
		// 分公司id
		String storeid = null;
		if (roidd == 2 || roidd == 3) {
			storeid = getPara("storeid");
			if (StrKit.isBlank(storeid)) {
				renderResult(11);
				return;
			}
		}

		// 账号
		String username = getPara("username");
		// 密码
		String password = getPara("password");
		// 真实姓名
		String trueName = getPara("trueName");
		// 手机号码
		String phonenumber = getPara("phonenumber");
		// 员工贡献分
		String contribution = getPara("contribution");
		// 性別
		int sex = getParaToInt("sex", 0);
		// 是否可用会员管理
		int VipPower = getParaToInt("VipPower", 0);
		// 是否可用
		int enabled = getParaToInt("enabled", 0);
		if (StrKit.isBlank(username)) {
			renderResult(1);
			return;
		} else if (username.length() > 20) {
			renderResult(2);
			return;
		} else if (adminService.findExistsByUsername(username)) {
			renderResult(3);
			return;
		} else if (StrKit.isBlank(password)) {
			renderResult(4);
			return;
		} else if (password.length() > 100) {
			renderResult(5);
			return;
		} else if (StrKit.isBlank(trueName)) {
			renderResult(6);
			return;
		} else if (trueName.length() > 20) {
			renderResult(7);
			return;
		} else if (StrKit.isBlank(phonenumber)) {
			renderResult(8);
			return;
		} else if (!ValidateKit.Mobile(phonenumber)) {
			renderResult(9);
			return;
		} else if (adminService.findExistsByPhonenumber(phonenumber)) {
			renderResult(10);
			return;
		}else {
			// 保存
			AdminSeller admin = new AdminSeller();
			admin.set("storeid", storeid).set("username", username)
					.set("password", new DefaultPasswordService().encryptPassword(password))
					.set("trueName", trueName)
					.set("phonenumber", phonenumber)
					.set("VipPower", VipPower)
					.set("enabled", enabled)
					.set("sex", sex)
					.set("contribution", contribution);
				//目前登录着的角色
				int roid = adminService.getRoles(userid);
				if (roid == 1) {//本身为超管 添加公司
					
					//超管给公司分配基础后台登录账户
					if (admin.save()){
						int sh = adminService.findadminByid(username);
							//	添加角色
						 adminService.findRoles(sh);
						renderSuccess();
						return;
					}
						
				} else if (roid == 2) {// 本身为公司  给分公司分配账号
					// 本身为公司  给分公司分配后台账号
					if (admin.save()){
						int DZ = adminService.findadminByid(username);
						//	添加角色
						 adminService.findRolesDj(DZ);
						renderSuccess();
					}
					return;
				}else if (roid == 3) {// 本身为分公司  添加营业部 同时用户表添加前端用户
					if (admin.save()){
						int DY = adminService.findadminByid(username);
						int UDY = adminService.findRolesSe(DY);
						if (UDY > 0){
							//userid就是当前登录用户的id
							//dy就是当前添加的adminseller的id即营业部的id，根据营业部id查出storeid，根据storeid查出t_dict_store的id，还有t_bus_seller的id
							Record findstoreidByUserId = adminService.findstoreidByUserId(userid);
							int stid = findstoreidByUserId.get("id");
							String sellerId = findstoreidByUserId.get("sellerId");
							//查出公司表id
							int seid = adminService.findSeidBySellerId(sellerId);
			    			//通过电话号码查询当前用户对象，即验证是否存在账号
			    			User userNew = adminService.findUserByPhone(phonenumber);
							//此手机号已经存在
							if (userNew!=null) {
								renderResult(10);
								return;
							} else {
								User user2 = new User();
								String date= DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
				    			//会员状态
				    			int state =1;
				    			//会员地址
				    			String address  = "请修改您的地址";
				    			String cards=DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS");
				    			String card=cards.substring(2);
								user2.set("name", trueName)
									.set("card", card)
								 	.set("phone", phonenumber)
								 	.set("state", state)
								 	.set("address", address)
								 	.set("sex", sex)
								 	.set("createDate", date)
								 	.set("toBossThreeId", seid)
									.set("toBossTwoId", stid)
								 	.set("babythday",DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
								 	.set("taici", SysConfig.tBusUserTaici.level_5)
								 	.set("password", CommonKit.encryptPassword(password));//设置用户密码，默认为手机号后六位
								//事务
								boolean flag = Db.tx(new IAtom() {
									@Override
									public boolean run() throws SQLException {
										return user2.save();
									}
								});
								if (flag) {
									 int tokerid = user2.get("id");
									 AdminSeller adminSeller = service.findAdseller(username);
									 //修改营业部在用户表里的关联id
									 adminSeller.set("tokerUserid", tokerid);
									 adminSeller.update();
									 //修改营业部所属营业部为他自己在t_auth_admin_seller表Id
									 user2.set("toBossOneId", adminSeller.getInt("id")).update();
									 renderSuccess();
								} else {
									logger.error("前端用户添加失败！");
								}
							}
						}
						renderSuccess();
						return;
					}
				}

		}
		renderFailed();
	}

	/**
	 * 添加二维码
	 */
	public void getQrCode() {
		int id = getParaToInt(0, 0);
		boolean post = adminService.getPost(id);
		if (post) {
			renderSuccess(adminService.findById(id));
			return;
		} else {
			renderFailed();
			return;
		}

	}

	// @RequiresPermissions("auth:admin:edit")
	public void toEdit() {
		int id = getParaToInt(0, 0);
		int userid = getCurrentUser().getInt("id");
		int roid = adminService.getRoles(userid);
		int etiroid = adminService.getRoles(id);
		setAttr("roid", roid);
		if (id != 0) {
			setAttr("object", adminService.findByIdAdmin(id));
		}
		if (roid == 1) {
			if(etiroid==2){
				render("selleredit.jsp");
			}else{
				Record store = adminService.findstoreidByUserId(id);
				setAttr("store", store);
			    render("edit.jsp");
			}
		} else if (adminService.findSelleridByUserId(userid) != null && roid == 2) {
			String sellerId = adminService.findSelleridByUserId(userid).get("sellerId");
			int VipPower= adminService.findSelleridByUserId(userid).getInt("VipPower");
			setAttr("VipPower", VipPower);
			setAttr("sellerId", sellerId);
			Record store = adminService.findstoreidByUserId(id);
			setAttr("store", store);
			render("edit.jsp");
		} else if (adminService.findstoreidByUserId(userid) != null && roid == 3) {
			Record store = adminService.findstoreidByUserId(id);
			int VipPower= adminService.findstoreidByUserId(userid).getInt("VipPower");
			setAttr("VipPower", VipPower);
			setAttr("store", store);
			render("edit.jsp");
		}
	}

	/**
	 * 更新
	 * 
	 * @return -1：异常，0：成功，1：姓名为空，2：姓名过长，3：手机号码为空，4：手机号码不正确，5：备注过长
	 */
	// @RequiresPermissions("auth:admin:edit")
	public void doEdit() {
		String userid = getPara("userid");

		int roidd = getParaToInt("Roid");
		// 分公司id
		String storeid = null;
		storeid = getPara("storeid");
		if (roidd == 2 || roidd == 3) {
			if (StrKit.isBlank(storeid)) {
				renderResult(11);
				return;
			}
		}
		// 真实姓名
		String trueName = getPara("trueName");
		String oldName = getPara("oldName");
		// 手机号码
		String phonenumber = getPara("phonenumber");
		// 员工贡献分
		String contribution = getPara("contribution");
		// 性別
		int sex = getParaToInt("sex", 0);
		// 是否可用会员管理
			int VipPower = getParaToInt("VipPower", 0);
		// 是否可用
		int enabled = getParaToInt("enabled", 0);
		
		if (StrKit.isBlank(userid)) {
			renderFailed();
			return;
		} else if (StrKit.isBlank(trueName)) {
			renderResult(1);
			return;
		} else if (trueName.length() > 20) {
			renderResult(2);
			return;
		} else if (StrKit.isBlank(phonenumber)) {
			renderResult(3);
			return;
		} else if (!ValidateKit.Mobile(phonenumber)) {
			renderResult(4);
			return;
		} /*
			 * else if(!StrKit.isBlank(remark)&&remark.length()>500){
			 * renderResult(5); return; }
			 */else {
			// 更新
			AdminSeller admin = new AdminSeller();
			admin.set("id", userid).set("storeid", storeid).set("trueName", trueName).set("phonenumber", phonenumber)
					.set("VipPower", VipPower).set("enabled", enabled).set("sex", sex).set("contribution", contribution);
			if (adminService.editUser(admin)) {
				adminService.setDaogou(trueName, oldName);//修改店员姓名
				renderSuccess(adminService.findById(Integer.valueOf(userid)));
				return;
			} 
		}
		renderFailed();
	}
	// @RequiresPermissions("auth:admin:edit")
	public void toEditPwd() {
		int id = getParaToInt(0, 0);
		if (id != 0) {
			setAttr("object", adminService.findByIds(id));
		}
		render("editPwd.jsp");
	}
   
	/**
	 * 更新密码
	 * 
	 * @return -1：异常，0：成功，1：密码为空，2：密码过长
	 */
	// @RequiresPermissions("auth:admin:edit")
	public void doEditPwd() {
		// 用户ID
		String userid = getPara("userid");
		// 密码
		String password = getPara("password");
		if (StrKit.isBlank(userid)) {
			renderFailed();
			return;
		} else if (StrKit.isBlank(password)) {
			renderResult(1);
			return;
		} else if (password.length() > 100) {
			renderResult(2);
			return;
		} else {
			// 更新
			if (adminService.editUser(new AdminSeller().set("id", userid).set("password",
					new DefaultPasswordService().encryptPassword(password)))) {
				renderSuccess();
				return;
			}
		}
		renderFailed();
	}

	/**
	 * 删除
	 * 
	 * @return -1：删除失败，0：删除成功
	 */
	// @RequiresPermissions("auth:admin:delete")
	public void doDelete() {
		int id = getParaToInt(0, 0);
		if (id != 0 && adminService.delUser(id)) {
			logger.info("删除用户【" + id + "】，并删除相应用户的角色关联信息");
			renderSuccess();
			return;
		}
		renderFailed();
	}

		//@RequiresPermissions("auth:admin:accredit")
		public void toAccredit() {
			
			int userid = getParaToInt(0,0);
			System.out.println(">>>>>>>"+userid);
			if (userid != 0) {
				setAttr("userid", getPara(0));
				int Selfuserid = getCurrentUser().getInt("id");
				int RolesId = roleService.findRolesId(Selfuserid);
				List<Record> roles = roleService.findAllRoles(RolesId);
				List<Record> selectedRoles = roleService.findRolesByUser(userid);
				for(Record role : roles){
					for(Record selected : selectedRoles){
						if(role.getInt("id")==selected.getInt("id")){
							role.set("checked", true);
							break;
						}else{
							role.set("checked", false);
							break;
						}
					}
				}
				System.out.println(roles);
				set("roles", roles);
				System.out.println(">>>>>>>");
			}
			render("accredit.jsp");
			System.out.println(">>>>>>>");
		}

		/**
		 * 用户角色设置
		 * 
		 * @return -1：失败，0：成功，1：没有选择角色
		 */
		// @RequiresPermissions("auth:admin:accredit")
		public void doAccredit() {
			int userid = getParaToInt("userid", 0);
			String[] roles = getParaValues("roleid");
			if (userid == 0) {
				renderFailed();
				return;
			} else if (roleService.saveUserRole(userid, roles)) {
				renderSuccess();
				return;
			}
			renderFailed();
		}
}
